<?php

declare(strict_types=1);

namespace app\common\model\Product;

use app\common\model\Config;
use app\common\model\User\User;
use think\Model;
use think\model\concern\SoftDelete;

/**
 * @mixin \think\Model
 */
class Product extends Model
{
    // 商品表
    protected $table = 'pre_product';

    use SoftDelete;

    // 软删除字段
    protected $deleteTime = 'deletetime';

    protected $append = [
        'cover_cdn', // 单图
        'vip_price',
        'thumbs_cdn',
        'flag_text'
    ];
    // 获取商品封面图
    public function getCoverCdnAttr($value, $data)
    {
        $cdn = Config::where(['key' => 'cdn'])->value('value');

        $thumbs = empty($data['thumbs']) ? [] : trim($data['thumbs']);

        if (empty($thumbs)) {
            return $cdn . '/static/home/res/images/avatar/default.png';
        }

        //字符串替换
        $thumbs = str_replace("upload/", $cdn . "/upload/", $thumbs);
        //转换为数组
        $list = json_decode($thumbs, true);
        if (count($list) > 0) {
            return $list[0];
        }
    }
    // 获取VIP价格
    public function getVipPriceAttr($value, $data)
    {
        $userid = request()->param('userid', 0);

        $vip = User::where(['id' => $userid])->value('vip');

        if (!$vip) {
            return false;
        }

        $price = Vip::where(['proid' => $data['id'], 'level' => $vip])->value('price');

        return $price;
    }
    // 获取商品所有图片
    public function getThumbsCdnAttr($value, $data)
    {
        $cdn = Config::where(['key' => 'cdn'])->value('value');

        $thumbs = empty($data['thumbs']) ? [] : trim($data['thumbs']);

        if (empty($thumbs)) {
            return $cdn . '/static/home/res/images/avatar/default.png';
        }

        //字符串替换
        $thumbs = str_replace("upload/", $cdn . "/upload/", $thumbs);

        //在转换为数组
        // $list = explode(',', $thumbs);
        $list = json_decode($thumbs, true);

        if (count($list) > 0) {
            return $list;
        }
    }
    // 商品状态
    public function getFlagTextAttr($value,$data){
        $FlagList = [1 => '新品', 2 => '热销', 3 => '推荐'];
        return $FlagList[$data['flag']];
    } 
    // 连表查询
    public function type(){
        return $this->belongsTo('app\common\model\Product\Type','typeid','id');
    }
}
